import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Card, Button, Descriptions, Tabs, List, message, Row, Col } from 'antd'
import { PlayCircleOutlined } from '@ant-design/icons'
import { courseService, orderService } from '../../services'

const CourseDetail = () => {
  const { id } = useParams()
  const navigate = useNavigate()
  const [course, setCourse] = useState<any>(null)
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    if (id) {
      loadCourseDetail()
    }
  }, [id])

  const loadCourseDetail = async () => {
    try {
      setLoading(true)
      const response: any = await courseService.getCourseById(id!)
      if (response.code === 200) {
        setCourse(response.data)
      }
    } catch (error) {
      console.error('Load course detail error:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleEnroll = async () => {
    try {
      // 创建订单
      const response: any = await orderService.createOrder({ courseId: id! })
      if (response.code === 201) {
        message.success('订单创建成功!')
        // 实际应该跳转到支付页面
        navigate('/my-courses')
      }
    } catch (error: any) {
      if (error.response?.data?.message?.includes('already purchased')) {
        message.info('您已购买此课程')
        navigate(`/courses/${id}/learn`)
      }
    }
  }

  if (!course) {
    return <div>加载中...</div>
  }

  return (
    <div style={{ maxWidth: '1200px', margin: '0 auto', padding: '24px' }}>
      <Row gutter={24}>
        <Col span={16}>
          <Card loading={loading}>
            <div style={{
              height: '400px',
              background: '#f0f2f5',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: '24px'
            }}>
              {course.cover ? (
                <img src={course.cover} alt={course.title} style={{ maxWidth: '100%', maxHeight: '100%' }} />
              ) : (
                <PlayCircleOutlined style={{ fontSize: '80px', color: '#999' }} />
              )}
            </div>

            <h1>{course.title}</h1>
            {course.subtitle && <p style={{ fontSize: '16px', color: '#666' }}>{course.subtitle}</p>}

            <Tabs
              items={[
                {
                  key: '1',
                  label: '课程介绍',
                  children: <div dangerouslySetInnerHTML={{ __html: course.description }} />,
                },
                {
                  key: '2',
                  label: '课程目录',
                  children: (
                    <List
                      dataSource={course.chapters || []}
                      renderItem={(chapter: any) => (
                        <List.Item>
                          <div>
                            <h4>{chapter.title}</h4>
                            <List
                              size="small"
                              dataSource={chapter.lessons || []}
                              renderItem={(lesson: any) => (
                                <List.Item>
                                  <PlayCircleOutlined style={{ marginRight: '8px' }} />
                                  {lesson.title}
                                  {lesson.isFree && <span style={{ color: '#52c41a', marginLeft: '8px' }}>免费</span>}
                                </List.Item>
                              )}
                            />
                          </div>
                        </List.Item>
                      )}
                    />
                  ),
                },
              ]}
            />
          </Card>
        </Col>

        <Col span={8}>
          <Card>
            <div style={{ fontSize: '32px', color: '#ff4d4f', fontWeight: 'bold', marginBottom: '16px' }}>
              ¥{course.price}
            </div>

            <Button type="primary" size="large" block onClick={handleEnroll}>
              立即购买
            </Button>

            <Descriptions column={1} style={{ marginTop: '24px' }}>
              <Descriptions.Item label="难度">{course.level}</Descriptions.Item>
              <Descriptions.Item label="学习人数">{course.studentCount}</Descriptions.Item>
              <Descriptions.Item label="讲师">{course.teacher?.user?.username}</Descriptions.Item>
              <Descriptions.Item label="分类">{course.category?.name}</Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
      </Row>
    </div>
  )
}

export default CourseDetail
